package com.example.demo.service;

import com.example.demo.entity.Authorit;
import com.example.demo.entity.Users;
import com.example.demo.mapper.AuthorityMapper;

import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;


import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class UserDutailsServicelmpl implements UserDetailsService {
    @Autowired
    HttpSession session;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AuthorityMapper authoritMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Users getuserbyname = userMapper.getuserbyname(username);
        if (getuserbyname==null){

            throw new RuntimeException("用户不存在");
        }else{
            List<Authorit>authoritList=new ArrayList<>();
            authoritList.add(authoritMapper.getAuthority(getuserbyname.getRid()));
            Collection<GrantedAuthority> authorities = new ArrayList<>();

            for (Authorit authorit1 : authoritList) {
                authorities.add(new SimpleGrantedAuthority(authorit1.getRole()));
            }
            session.setAttribute("username",getuserbyname.getUsername());
            return new org.springframework.security.core.userdetails.User(getuserbyname.getUsername(),
                    getuserbyname.getPassword(), authorities);
        }
    }
}
